const { Student, ImgSchema, School } = require("../model");
const multer = require('multer');
const express = require("express");
const router = express.Router();


const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

router.post('/upload', async (req, res) => {
  console.log(req.file);
  console.log(req.body);
  // const image = new ImgSchema({
  //   name: req.body.name,
  //   data: req.file.buffer,
  //   id: req.body.id,
  // });
  res.status(200).send(req);

});

// 上传图片
/**
 * data.append('data', buffer));
 * body.id = _id
 */
router.post('/upload1', upload.single('data'), async (req, res) => {
  console.log(req.file);
  const image = new ImgSchema({
    name: req.body.name,
    data: req.file.buffer,
    id: req.body.id,
  });

  try {
    await image.save();
    res.status(200).send('Image saved successfully.');
  } catch (error) {
    console.error(error);
    res.status(500).send('Failed to save image.');
  }
});



// 查找图片:id
router.post('/find', async (req, res) => {
  const id = req.body.id;
  try {
    const image = await ImgSchema.findOne({ id });

    if (!image) {
      res.status(404).send('Image not found.');
      return;
    }

    res.setHeader('Content-Type', 'image/jpeg');
    res.send(image.data);
  } catch (error) {
    console.error(error);
    res.status(500).send('Failed to retrieve image.');
  }
});


// 获取所有学校列表
router.post("/getSchoolList", async (q, s) => {
  const doc = await School.find(); // 参数是查询参数，精确匹配，结果是匹配的数组
  s.send({
    msg: "获取成功",
    success: true,
    data: doc,
  });
});


module.exports = router;
